package apis

import (
	"QImages/database"
	"QImages/entity"
	"QImages/serializer"
	"QImages/utils"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

// GetUserInfoByToken 根据token获取用户信息
func GetUserInfoByToken(c *gin.Context) {
	token := c.Param("token")
	user, err := entity.FindUserByToken(token)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.Err(serializer.CodeForbidden, "无效token", nil))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("获取用户信息成功", serializer.BuildUser(&user)))
}

// Login 用户登录
func Login(c *gin.Context) {
	var param struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}
	err := c.Bind(&param)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr("", nil))
	}
	var user = entity.User{
		Username: param.Username,
		Password: param.Password,
	}
	if err := entity.CheckUser(&user); err == nil {
		log.Println(err)
		// 生成token
		user.Token = utils.Md5token()
		database.DB.Model(&user).Update("token", user.Token)
		c.JSON(http.StatusOK, serializer.OK("登陆成功", user.Token))
	} else {
		log.Println("login error : ", err)
		c.JSON(http.StatusOK, serializer.Err(serializer.CodeLoginFailed, "用户名或密码错误，登录失败", nil))
	}

}

type ParamUser struct {
	Avatar   string `json:"url"  binding:"required"`
	Nickname string `json:"nickname"  binding:"required"`
	Username string `json:"username"  binding:"required"`
	Password string `json:"password"  binding:"required"`
}

// Register 用户注册
func Register(c *gin.Context) {
	var param ParamUser
	err := c.ShouldBindJSON(&param)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr("", err))
		return
	}
	result := database.DB.Where("username=?", param.Username).Find(&entity.User{})
	if result.Error == nil {
		log.Println(result.Error)
		c.JSON(http.StatusOK, serializer.Err(serializer.CodeUserExist, "用户名已存在", nil))
		return
	}
	user := entity.User{
		Username:  param.Username,
		Password:  param.Password,
		Name:      param.Nickname,
		AvatarUrl: param.Avatar,
	}
	id, err := user.Insert()
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.DBErr("数据库异常，注册失败", err))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("注册成功", id))
}
